﻿using UnityEngine;
using UnityEngine.AI;

namespace Gp.Scripts.Character {
    [RequireComponent(typeof(BaseCharacter))]
    public class CharacterFallenFix : MonoBehaviour{
        [SerializeField] private float recallTime = 1f;
        
        
        private Vector3 _lastPos = Vector3.zero;
        private BaseCharacter _character;
        // private float _fallDistance;

        private float _fallTime;

        private bool _recorded = false;
        private void Start() {
            _character = GetComponent<BaseCharacter>();
        }

        private void Update() {
            var isGrounded = _character.IsGrounded();
            if (isGrounded) {
                _fallTime = 0;
                RecodePos();
            }
            else {
                IncFallHeight();
            }

            if (RecallJudge()) {
                ResetPos();
            } 
        }




        private bool RecallJudge() {
            return _fallTime >= recallTime;
        }
        
        
        
        
        
        

        private void IncFallHeight() {
            if (!_recorded) return;
            // _fallDistance += Math.Max(0, _lastPos.y - transform.position.y);
            _fallTime += Time.deltaTime;
        }
        
        
        
        private void RecodePos() {
            if (!NavMesh.SamplePosition(transform.position, out var hit, .2f, 1)) {
                return;
            }

            _recorded = true;
            _lastPos = transform.position;
        }

        private void ResetPos() {
            if (!_recorded) return;
            transform.position = _lastPos;
        }


        private void OnEnable() {
            if (this.TryGetComponent<PlayerBaseCharacter>(out var target)) {
                target.EnableFallenFix = true;
            }
        }
        
        private void OnDisable() {
            if (this.TryGetComponent<PlayerBaseCharacter>(out var target)) {
                target.EnableFallenFix = false;
            }
        }
    }
}